//
//  MSAllListViewController.m
//  MSJD
//
//  Created by 箭军刘 on 2018/10/15.
//  Copyright © 2018年 xiangbo. All rights reserved.
//

#import "MSAllListViewController.h"

#import "MSDetailViewController.h"

#import "MSEmptyView.h"
#import "MSAllListCollectionCell.h"
#import "MSCollectionBaseCell.h"
#import "MSTemplateCellDefine.h"

#import "MSAllListDataSource.h"

@interface MSAllListViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) MSEmptyView *emptyView;

@property (nonatomic, strong) MSFoodData *foodData; // 上级页面传入的参数
@property (nonatomic, copy) NSArray *dataSource; // 当前列表展示的数据

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageSize;

@end

@implementation MSAllListViewController

+ (instancetype)loadAllListViewControllerWithFoodData:(MSFoodData *)foodData {
    MSAllListViewController *allListVC = [[MSAllListViewController alloc] init];
    allListVC.foodData = foodData;
    return allListVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 1;
    self.pageSize = 5;
    self.view.backgroundColor = rgb(242, 242, 242);
    self.navigationItem.title = [MSSafeObject stringInfo:self.foodData.title];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = UIColorHex(0xdddddd);
    [self.view addSubview:lineView];
    
    [self.view addSubview:self.collectionView];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(0.5);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.top.equalTo(lineView.mas_bottom);
    }];
    
    [self.collectionView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}
/** 加载数据 */
- (void)loadAllListDataFromServer {
    _WEAKSELF
    NSInteger foodId = [self.foodData.mId integerValue];
    NSInteger kindId = [self.foodData.kind integerValue];
    NSString *url = @"v1/content/list";
    if (![MSSafeObject isNull:self.foodData.url]) {
        url = self.foodData.url;
    } else {
        if ([self.foodData.showType isEqualToString:@"popular"]) {
            // 最受欢迎餐厅
            url = @"v1/item/popular";
        } else if ([self.foodData.showType isEqualToString:@"suggest"]) {
            // 推荐美食
            url = @"v1/item/suggest";
        }
    }
    [MSAllListDataSource queryFoodListDataWithUrl:self.foodData.url FoodId:foodId kindId:kindId page:self.page pageSize:self.pageSize success:^(MSFoodNearbyData * _Nonnull responseInfo) {
        [weakSelf stopRefresh];
        [weakSelf loadAllListDataSuccess:responseInfo];
    } failure:^(NSError * _Nonnull error) {
        [weakSelf stopRefresh];
        NSString *errorMsg = error.localizedDescription?:@"获取数据失败";
        [weakSelf loadAllListDataFailure:errorMsg];
    }];
}

#pragma mark - UICollectionDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= self.dataSource.count) {
        return [UICollectionViewCell alloc];
    }
    NSString *cellName = [self getCollectionViewCellNameWithShowType:self.foodData.showType];
    MSCollectionBaseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellName forIndexPath:indexPath];
    cell.modelData = self.dataSource[indexPath.row];
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (indexPath.row >= self.dataSource.count) {
        return;
    }
    MSFoodDetailData *rowModel = self.dataSource[indexPath.row];
    [MSJumpConn jumpToMSDetailViewController:rowModel];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 20, 10, 20);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self collectionCellSizeWithShowType:self.foodData.showType];
}

#pragma mark - Event Reponse
/** 返回按钮点击 */
- (void)backButtonClick {
    [self.navigationController popViewControllerAnimated:YES];
}
/** 头部刷新 */
- (void)headerRefresh {
    self.page = 1;
    [self loadAllListDataFromServer];
}
/** 底部刷新 */
- (void)footerRefresh {
    [self loadAllListDataFromServer];
}

#pragma mark - Private Method
/** 加载数据成功 */
- (void)loadAllListDataSuccess:(MSFoodNearbyData *)response {
    NSArray *rows = response.rows;
    if (self.page == 1) {
        // 头部刷新
        self.dataSource = rows;
        if (self.dataSource.count < 1) {
            NSString *emptyMsg = @"没有查询到对应的数据";
            [self showEmptyViewWithType:0 message:emptyMsg];
            return;
        }
        [self.collectionView reloadData];
    } else {
        // 加载更多
        NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.dataSource];
        [tempArr addObjectsFromArray:rows];
        self.dataSource = tempArr.copy;
        [self.collectionView reloadData];
    }
    // footer的状态
    self.collectionView.mj_footer.hidden = NO;
    NSInteger totalPage = [response.totalPage integerValue];
    NSInteger page = [response.page integerValue];
    if (totalPage <= page) {
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    } else {
        self.page ++;
    }
}
/** 加载数据失败 */
- (void)loadAllListDataFailure:(NSString *)errorMsg {
    [MBProgressHUD showToastWithMessage:errorMsg toView:self.view];
    if (self.dataSource.count < 1) {
        [self showEmptyViewWithType:MSEmptyTypeRetry message:@"查询数据失败"];
    }
}
/** 展示空界面 */
- (void)showEmptyViewWithType:(MSEmptyType)type message:(NSString *)message {

    MSEmptyView *emptyView = [MSEmptyView loadEmptyViewWithType:type toast:message frame:CGRectMake(0, 0, MS_SCREEN_WIDTH, MS_SCREEN_HEIGHT)];
    // 重试按钮点击
    _WEAKSELF
    emptyView.RetryButtonClickBlock = ^{
        [weakSelf loadAllListDataFromServer];
    };
    [self.view addSubview:emptyView];
    self.emptyView = emptyView;
}

- (void)stopRefresh {
    if ([self.collectionView.mj_header isRefreshing]) {
        [self.collectionView.mj_header endRefreshing];
    }
    if ([self.collectionView.mj_footer isRefreshing]) {
        [self.collectionView.mj_footer endRefreshing];
    }
}
/** 根据模块的类型获取cell */
- (NSString *)getCollectionViewCellNameWithShowType:(NSString *)showType {
//    if ([showType isEqualToString:@"popular"]) {
//        return @"MSTypeBCollectionCell";
//    }
    NSString *identify = MSRedirectIdentifierDic[showType];
    return identify ?: @"MSCollectionBaseCell";
}
/** 根据showType来获取cell的size */
- (CGSize)collectionCellSizeWithShowType:(NSString *)showType {
    /* showType: popular 大横图 + 主标题 + 评分 + 位置
     suggest:   两个一行(小横图 + 主标题 + 评分 + 位置)
     db_vimg:   两个一行(竖图 + 内嵌主标题 + 内嵌汇总数)
     */
    if ([showType isEqualToString:@"popular"]) {
        return CGSizeMake(MS_SCREEN_WIDTH - 2 * 20, 227);
    } else if ([showType isEqualToString:@"suggest"] ||
               [showType isEqualToString:@"db_himg"]) {
        return CGSizeMake(MS_SCREEN_WIDTH / 2 - 25, 206);
    } else if ([showType isEqualToString:@"db_vimg"]) {
        return CGSizeMake(MS_SCREEN_WIDTH / 2 - 25,  210);
    }
    return CGSizeZero;
}

#pragma mark - Setter And Getter

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        // 不同的数据类型注册不同的cell
        NSString *showType = self.foodData.showType;
        NSString *cellName = [self getCollectionViewCellNameWithShowType:showType];
        if (![MSSafeObject isNull:cellName]) {
            [_collectionView registerClass:[NSClassFromString(cellName) class] forCellWithReuseIdentifier:cellName];
        }

        MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
        footer.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        footer.hidden = YES;
        _collectionView.mj_footer = footer;

        MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
        header.stateLabel.textColor = MSThemeColor;
        header.lastUpdatedTimeLabel.alpha = 1.0;
        _collectionView.mj_header = header;
    }
    return _collectionView;
}

#pragma mark -  Memory Method

- (void)dealloc {
    NSLog(@"%s", __func__);
}

@end
